package subjectLibrary.dao;

import subjectLibrary.Util.DBUtil;
import subjectLibrary.question.Question;
import subjectLibrary.question.math.FourAirthmetic;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class ExerciseDao {
    DBUtil db = new DBUtil();

    /**
     * 插入题目
     * @param question
     * @throws Exception
     */
    public void insertExercise(Question question) throws Exception {
        Connection conn = db.getConn();
        PreparedStatement pstm = null;
        String sql_insert = "insert into exercise(question, answer) values(?,?)";	//sql语言
        pstm = conn.prepareStatement(sql_insert);

        //填充sql语句中的？
        pstm.setString(1, question.getQuestion());
        pstm.setString(2, question.getAnswer());

        //使用executeUpdate函数执行sql语句
        int row = pstm.executeUpdate();
        System.out.println("新增题目成功" + row + "行受到影响");
        //释放对数据库的连接
        db.closeConn(null, pstm, conn);
    }

    public List<Question> selectExercise(int num) throws Exception {
        Connection conn = db.getConn();
        PreparedStatement pstm = null;
        String sql_select = "SELECT * FROM exercise LIMIT ?";	//sql语言
        pstm = conn.prepareStatement(sql_select);
        pstm.setInt(1, num);
        ResultSet rs= pstm.executeQuery();

        List<Question> questionList = new ArrayList<>();
        while (rs.next()) {
            System.out.println(rs.getString("question") + " " + rs.getString("answer"));
            Question question = new FourAirthmetic();
            question.setQuestion(rs.getString("question"));
            question.setAnswer(rs.getString("answer"));
            questionList.add(question);
        }
        db.closeConn(rs, pstm, conn);
        return questionList;
    }

    public static void main(String[] args) {
        List<Question> questionList = new ArrayList<>();
        try {
            ExerciseDao exerciseDao = new ExerciseDao();
            questionList = exerciseDao.selectExercise(10);
            for (Question question : questionList) {
                System.out.println(question.getQuestion());
                System.out.println(question.getAnswer());
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
